import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:media_kit/media_kit.dart';
import 'package:private_journey/GlobalInfo.dart';
import 'package:private_journey/pages/clipboardPage.dart';
import 'package:private_journey/pages/home.dart';
import 'package:private_journey/pages/mailPage.dart';
import 'package:private_journey/pages/music.dart';
import 'package:private_journey/pages/todo.dart';
import 'package:private_journey/pages/trending.dart';
import 'package:private_journey/services/DbService.dart';
import 'package:private_journey/services/KService.dart' as KService;
import 'package:shadcn_flutter/shadcn_flutter.dart' as shadcn;
import 'package:signals/signals_flutter.dart';
import 'package:window_manager/window_manager.dart';

import 'States.dart';
import 'pages/settings.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (Platform.isWindows) {
    await windowManager.ensureInitialized();
  }
  MediaKit.ensureInitialized();
  DbService.init();
  KService.init();
  runApp(const MyApp());
}

GoRouter router = GoRouter(
  routes: [
    ShellRoute(
      routes: [
        GoRoute(
          path: '/home',
          builder: (context, state) {
            return TrendingPage();
          },
        ),
        GoRoute(
          path: '/trending',
          builder: (context, state) {
            return Home();
          },
        ),
        GoRoute(
          path: '/subscription',
          builder: (context, state) {
            return SettingsPage();
          },
        ),
        GoRoute(
          path: '/music',
          builder: (context, state) {
            return MusicPage();
          },
        ),
        GoRoute(
          path: '/clipboard',
          builder: (context, state) {
            return Clipboardpage();
          },
        ),
        GoRoute(
          path: '/mail',
          builder: (context, state) {
            return EmailApp();
          },
        ),
        GoRoute(
          path: '/todo',
          builder: (context, state) {
            return todoPage();
          },
        ),
      ],
      builder: (context, state, child) {
        return MyHomePage(child: child);
      },
    ),
  ],
  initialLocation: '/home',
);

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() =>
      Platform.isWindows ? _MyAppStateWindows() : _MyAppState();
}

class LifecycleEventHandler extends WidgetsBindingObserver {
  final Future<bool> Function() detachedCallBack;

  LifecycleEventHandler({required this.detachedCallBack});

  @override
  Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
    if (state == AppLifecycleState.detached) {
      await detachedCallBack();
    }
  }
}

class _MyAppStateWindows extends State<MyApp> with WindowListener {
  shadcn.ColorScheme colorScheme = shadcn.ColorSchemes.lightRose();

  Future<void> initKeys() async {
    var keys = await getUserKeysConfig();
    var s = <KeyCodeInfo, int>{};
    for (var e in keys) {
      s[e.keyCodeInfo] = e.count;
    }
    keyMap.value = s;
    // 初始化键盘服务
    Future.delayed(Duration(seconds: 3), () async {
      var socket = await WebSocket.connect('ws://localhost:8080/ws');
      socket.listen(
        (data) {
          logger.d('Received: $data');

          var d = jsonDecode(data);
          if (d['type'] != 'keyup' && d['type'] != 'keydown') return;
          var state =
              d['type'] == 'keydown' ? KeyState.pressed : KeyState.released;
          var keycodeinfo = KeyCodeInfo('', d['data']['rawcode'], state: state);
          // keycodeinfo.code = d['data']['rawcode'];
          keyCodeInfo.value = keycodeinfo;

          if (keyCodeInfos.value.contains(keycodeinfo)) {
            keyCodeInfos.value.remove(keycodeinfo);
          }
          keyCodeInfos.value = [...keyCodeInfos.value, keycodeinfo];
          //快捷键处理
          var lctrl =
              keyCodeInfos.value.where((e) {
                return e.code == 162;
              }).firstOrNull;
          var key_c =
              keyCodeInfos.value.where((e) {
                return e.code == 67;
              }).firstOrNull;
          if (lctrl != null &&
              key_c != null &&
              lctrl.state == KeyState.pressed &&
              key_c.state == KeyState.pressed) {
            logger.i('you click the combination keys ctrl+c');
          }

          var e1 =
              keyMap.value.keys.where((e) {
                return e.code == keycodeinfo.code;
              }).firstOrNull;
          if (e1 != null && state == KeyState.released) {
            e1.state = state;
            Map<KeyCodeInfo, int> map = Map.from(keyMap.value);
            var total = map[e1]! + 1;
            map[e1] = total;
            keyMap.value = map;
            updateUserKeysConfig(e1, keyTotal: total);
          }
        },
        onError: (e) {
          // log.e('Error: $e');
        },
        onDone: () {},
        cancelOnError: false,
      );
    });
  }

  @override
  void initState() {
    super.initState();
    initKeys();
  }

  @override
  void onWindowClose() {
    print('close');
    super.onWindowClose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Watch((context) {
      return shadcn.ShadcnApp.router(
        theme: shadcn.ThemeData(
          colorScheme: currentColorScheme.value,
          radius: 0.5,
        ),
        routerConfig: router,
        debugShowCheckedModeBanner: false,
      );
    });
  }
}

class _MyAppState extends State<MyApp> {
  shadcn.ColorScheme colorScheme = shadcn.ColorSchemes.lightRose();

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Watch((context) {
      return shadcn.ShadcnApp.router(
        theme: shadcn.ThemeData(
          colorScheme: currentColorScheme.value,
          radius: 0.5,
        ),
        routerConfig: router,
        debugShowCheckedModeBanner: false,
      );
    });
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.child});

  final Widget child;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(body: MainContent(child: widget.child));
  }
}

class MainContent extends StatelessWidget {
  final Widget child;

  const MainContent({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    return Row(children: [LeftSidebar(), Flexible(child: child)]);
  }
}

class RightZone extends StatelessWidget {
  const RightZone({super.key});

  @override
  Widget build(BuildContext context) {
    return Flexible(child: Container(color: Colors.pink));
  }
}

class LeftSidebar extends StatefulWidget {
  const LeftSidebar({super.key});

  @override
  State<LeftSidebar> createState() => _LeftSidebarState();
}

class _LeftSidebarState extends State<LeftSidebar> {
  bool expanded = true;
  int selected = 0;

  shadcn.NavigationItem buildButton(
    String text,
    IconData icon,
    ValueChanged<bool>? f,
  ) {
    return shadcn.NavigationItem(
      label: Text(text),
      alignment: Alignment.centerLeft,
      onChanged: f,
      // selectedStyle: const ButtonStyle.primaryIcon(),
      child: Icon(icon),
    );
  }

  shadcn.NavigationLabel buildLabel(String label) {
    return shadcn.NavigationLabel(
      alignment: Alignment.centerLeft,
      child: Text(label).semiBold().muted(),
      // padding: EdgeInsets.zero,
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return shadcn.NavigationRail(
      backgroundColor: theme.colorScheme.primaryContainer,
      labelType: shadcn.NavigationLabelType.expanded,
      labelPosition: shadcn.NavigationLabelPosition.end,
      alignment: shadcn.NavigationRailAlignment.start,
      expanded: expanded,
      index: selected,
      onSelected: (value) {
        setState(() {
          selected = value;
        });
      },
      children: [
        shadcn.NavigationButton(
          alignment: Alignment.centerLeft,
          label: const Text('Menu'),
          onPressed: () {
            setState(() {
              expanded = !expanded;
            });
          },
          child: const Icon(Icons.menu),
        ),
        const shadcn.NavigationDivider(),
        buildLabel('You'),
        buildButton('Home', Icons.home_filled, (value) {
          if (value) {
            if (context.canPop()) {
              context.pop();
            }
            context.push('/home');
          }
        }),
        buildButton('Trending', Icons.trending_up, (value) {
          if (value) {
            if (context.canPop()) {
              context.pop();
            }
            context.push('/trending');
          }
        }),
        buildButton('Subscription', Icons.subscriptions, (value) {
          if (value) {
            if (context.canPop()) {
              context.pop();
            }
            context.push('/subscription');
          }
        }),
        const shadcn.NavigationDivider(),
        buildLabel('History'),
        buildButton('clipboard', Icons.copy, (value) {
          if (value) {
            if (context.canPop()) {
              context.pop();
            }
            context.push('/clipboard');
          }
        }),
        buildButton('drawboard', Icons.draw_rounded, (value) {
          if (value) {
            if (context.canPop()) {
              context.pop();
            }
            context.push('/drawboard');
          }
        }),
        buildButton('mail', Icons.mail, (value) {
          if (value) {
            if (context.canPop()) {
              context.pop();
            }
            context.push('/mail');
          }
        }),
        const shadcn.NavigationDivider(),
        buildLabel('Movie'),
        buildButton('todo list', Icons.today_outlined, (value) {
          if (value) {
            if (context.canPop()) {
              context.pop();
            }
            context.push('/todo');
          }
        }),
        buildButton('music', Icons.music_note_rounded, (value) {
          if (value) {
            if (context.canPop()) {
              context.pop();
            }
            context.push('/music');
          }
        }),
        buildButton('Thriller', Icons.movie, null),
        const shadcn.NavigationDivider(),
        buildLabel('Short Films'),
        buildButton('book', Icons.book, null),
        buildButton('Horror', Icons.movie_creation_outlined, null),
      ],
    );
  }
}
